import axios from "axios";

export async function copyToClipboard(text) {
  if(navigator?.clipboard?.writeText) {
    return navigator.clipboard.writeText(text)
  }
  const textarea = document.createElement('textarea');
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

export async function exportExcel(data, filename?: string) {
  return axios({
    method: 'POST',
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    headers: { token: localStorage.getItem('token') },
    url: '/ykf/excel/download',
    data: data,
    responseType: 'blob',
  }).then(res => {
    return new Promise((resolve, reject) => {
      const reader =  new FileReader()
      reader.readAsDataURL(res.data)
      reader.onload = (e) => {
        let name = filename
        const contentDisposition = res.headers.get('Content-Disposition');
        if (!name && contentDisposition) {
          // 解析Content-Disposition头来提取文件名
          name = contentDisposition.split(`attachment;filename*=utf-8''`)[1].trim().replace(/\"/g, '');
          const [n, h] = name.split('.')
          name = `${decodeURIComponent(n)}.${h}`
        }

        const a = document.createElement('a')
        a.download = name
        a.href = e.target.result as string
        document.body.append(a)
        a.click()
        document.body.removeChild(a)
        resolve(0)
      }
      reader.onerror = e => {
        reject(e)
      }
    })
  })
}
